//
//  CGRegistViewController.m
//  SchoolClient
//
//  Created by mac on 15/11/2.
//  Copyright © 2015年 mac. All rights reserved.
//
/*
 {"id":"cu-89c47011-7d2f-4cbc-acd6-9debe1e949d1","name":"xiaohu","account":"ergou29","password":"ktoUOvkNIFgprgwu2N7M2ZgPzdLfj8ds1RMCIgMpF0Ts2uTZGmQ","tphone":"18278927527","accountStatus":1}
 */

#import "CGRegistViewController.h"


@interface CGRegistViewController ()<UITextFieldDelegate,UIAlertViewDelegate>

@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)CGRegistTextView *accountText;          //账号
@property(nonatomic,strong)CGRegistTextView *passwordText;         //密码
@property(nonatomic,strong)CGRegistTextView *passwordTooText;      //再次输入密码
@property(nonatomic,strong)CGRegistTextView *phoneText;            //手机号
@property(nonatomic,strong)CGRegistTextView *verifyText;           //验证码
@property(nonatomic,strong)UIButton *registButton;                 //注册
@property(nonatomic,strong)JKCountDownButton *verifyButton;        //验证码
@property(nonatomic,assign)CGFloat textFontSize;
//注册的内容
@property(nonatomic,strong)NSString *account;
@property(nonatomic,strong)NSString *password;
@property(nonatomic,strong)NSString *passowrdToo;
@property(nonatomic,strong)NSString *phone;
@property(nonatomic,strong)NSString *verify;
//协议窗口
@property(nonatomic,strong)UIWindow *protocolWindow;
@property(nonatomic,strong)UIView *protocolView;

@property(nonatomic,strong)UIWindow *coverWindow;
@property(nonatomic,strong)UIView *shadeView;
@property(nonatomic,strong)UIActivityIndicatorView *activity;
@property(nonatomic,strong)UILabel *indicateLabel;

@property(nonatomic,assign)BOOL isComeBack;

@end

#define TEXT_MARGIN 10    //文本框的边距
//#define TEXT_HEIGHT 44
@implementation CGRegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"注册";
    self.view.backgroundColor = [Tools getColor:@"ebebeb"];
    
    self.textFontSize = 15;
    [self layoutUI];
}

-(void)layoutUI{
    
    //底部添加一个scrollowView {{0, 0}, {320, 480}}
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 480-64-50)];
    self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, 336 + 120);
    //self.scrollView.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:self.scrollView];
    
    CGRect aFrame = CGRectMake(20, 10, SCREEN_WIDTH - 20 - 20, 44);
    //账号
    self.accountText = [[CGRegistTextView alloc]initWithFrame:aFrame andImageName:@"login_phone_icon"];
    self.accountText.textField.placeholder = @"请输入账号";
    self.accountText.textField.delegate = self;
    [self.accountText.textField becomeFirstResponder];
    [self.scrollView addSubview:self.accountText];
    [self.accountText.textField addTarget:self action:@selector(accountInputFinish) forControlEvents:UIControlEventEditingDidEnd];
    
    //密码
    aFrame.origin.y = CGRectGetMaxY(self.accountText.frame) + TEXT_MARGIN;
    self.passwordText = [[CGRegistTextView alloc]initWithFrame:aFrame andImageName:@"login_password_icon"];
    self.passwordText.textField.placeholder = @"请输入密码";
    self.passwordText.textField.delegate = self;
    self.passwordText.textField.secureTextEntry = YES;
    //self.passwordText.textField.enabled = NO;
    [self.scrollView addSubview:self.passwordText];

    
    //再次输入密码
    aFrame.origin.y = CGRectGetMaxY(self.passwordText.frame) + TEXT_MARGIN;
    self.passwordTooText = [[CGRegistTextView alloc]initWithFrame:aFrame andImageName:@"login_password_icon"];
    self.passwordTooText.textField.placeholder = @"请再次输入密码";
    self.passwordTooText.textField.delegate = self;
    self.passwordTooText.textField.secureTextEntry = YES;
    //self.passwordTooText.textField.enabled = NO;
    [self.scrollView addSubview:self.passwordTooText];

    
    //手机号
    aFrame.origin.y = CGRectGetMaxY(self.passwordTooText.frame) + TEXT_MARGIN;
    self.phoneText = [[CGRegistTextView alloc]initWithFrame:aFrame andImageName:@"login_phone_icon"];
    self.phoneText.textField.placeholder = @"请输入手机号";
    self.phoneText.textField.delegate = self;
    //self.phoneText.textField.enabled = NO;
    [self.scrollView addSubview:self.phoneText];

    
    //验证码
    aFrame.origin.y = CGRectGetMaxY(self.phoneText.frame) + TEXT_MARGIN;
    aFrame.size.width = SCREEN_WIDTH - 20 - 110;
    self.verifyText = [[CGRegistTextView alloc]initWithFrame:aFrame andImageName:@"login_very_icon"];
    self.verifyText.textField.placeholder = @"请输入验证码";
    self.verifyText.textField.delegate = self;
    self.verifyText.textField.enabled = NO;
    [self.scrollView addSubview:self.verifyText];
    
    //获取验证码Button
    aFrame.origin.x = SCREEN_WIDTH - 100;
    aFrame.size.width = 80;
    self.verifyButton = [[JKCountDownButton alloc]initWithFrame:aFrame];
    [self.verifyButton setBackgroundImage:[UIImage imageNamed:@"login_very_btn_bg"] forState:UIControlStateNormal];
    [self.verifyButton setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.verifyButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    self.verifyButton.titleLabel.font = [UIFont boldSystemFontOfSize:13];
    [self.scrollView addSubview:self.verifyButton];
    [self.verifyButton addTarget:self action:@selector(getVerfyCode:) forControlEvents:UIControlEventTouchUpInside];
    self.verifyButton.enabled = NO;
    
    //注册Button
    aFrame.origin.y = CGRectGetMaxY(self.verifyText.frame) + 20;
    aFrame.origin.x = 20;
    aFrame.size.width = SCREEN_WIDTH - 40;
    self.registButton = [[UIButton alloc]initWithFrame:aFrame];
    [self.registButton setBackgroundImage:[UIImage imageNamed:@"login_btn_bg"] forState:UIControlStateNormal];
    [self.registButton setTitle:@"立即注册" forState:UIControlStateNormal];
    self.registButton.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [self.scrollView addSubview:self.registButton];
    //添加点击事件
    [self.registButton addTarget:self action:@selector(tapRegistButton:) forControlEvents:UIControlEventTouchUpInside];
    self.registButton.enabled = NO;
    
    
    //声明label
    aFrame.origin.y = CGRectGetMaxY(self.registButton.frame);
    aFrame.size.height = 30;
    UILabel *defineLabel = [[UILabel alloc]initWithFrame:aFrame];
    defineLabel.backgroundColor = [UIColor clearColor];
    //defineLabel.text = @"点击\"登录\"，即表示你同意《美栗婷免责声明》";
    //点击上面的注册按钮，即表示您已查看并同意《使用条款》
    defineLabel.textAlignment = NSTextAlignmentCenter;
    defineLabel.font = [UIFont systemFontOfSize:12];
    
    //NSString *string = @"点击\"登录\"，即表示你同意《美栗婷免责声明》";
    NSString *string = @"点击注册按钮,即表示您已查看并同意《使用条款》";
    NSRange range = [string rangeOfString: @"《使用条款》"];
    //创建一个可变的属性字符串
    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc]initWithString: string];
    [attribute addAttributes:@{NSForegroundColorAttributeName:[Tools getColor:@"43bee0"]} range:range];
    defineLabel.text = string;
    [defineLabel setAttributedText: attribute];
    [self.scrollView addSubview:defineLabel];
    
    
    
}


#pragma mark 获取验证码事件
-(void)getVerfyCode:(JKCountDownButton *)sender{
    
    //1.有效性验证,去除字符串两端的空格
    if (![Tools isMobileNumber:self.phoneText.textField.text]) {
        
        [Tools alertWithTitle:@"温馨提示" andMessage:@"请输入正确的手机号码"];
        return;
    }
    
    self.password = [self.passwordText.textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    self.passowrdToo = [self.passwordTooText.textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    self.phone = [self.phoneText.textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if (self.account.length == 0){
        [Tools alertWithTitle:@"温馨提示" andMessage:@"请输入账号"];
        return;
    }else if (![self.password isEqualToString:self.passowrdToo] || self.password.length == 0){
        [Tools alertWithTitle:@"温馨提示" andMessage:@"密码输入有误,请重新输入!"];
        return;
    }

    
    //2.发送请求获取验证码
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"tphone"] = self.phoneText.textField.text;
    
    ZYHRequest *request = [ZYHRequest new];
    NSData *responseData = [request getSyncEncryptRequest:@"/main/getCode.app?" parameters:parameters];
    NSString *result = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"result:%@",result);
    if ([result isEqualToString:@"1"]) {
        self.verifyText.textField.enabled = YES;
        [self.verifyText.textField becomeFirstResponder];
        self.registButton.enabled = YES;
    }else{
        [Tools alertWithTitle:@"温馨提示" andMessage:@"系统繁忙,请稍后再试"];
        return;
    }
    //倒计时
    sender.enabled = NO;
    [sender startWithSecond:60];
    [sender didChange:^NSString *(JKCountDownButton *countDownButton, int second) {
        NSString *title = [NSString stringWithFormat:@"剩%d秒",second];
        return title;
    }];
    [sender didFinished:^NSString *(JKCountDownButton *countDownButton, int second) {
        countDownButton.enabled = YES;
        return @"重新获取";
    }];
    
}


#pragma mark 注册点击事件
-(void)tapRegistButton:(UIButton *)sender{
    
    self.verify = [self.verifyText.textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if (![self.password isEqualToString:self.passowrdToo] || self.password.length == 0) {
        [Tools alertWithTitle:@"温馨提示" andMessage:@"密码输入有误,请重新输入!"];
        return;
    }else if (self.account.length == 0){
        [Tools alertWithTitle:@"温馨提示" andMessage:@"请输入账号"];
        return;
    }else if (![Tools isMobileNumber:self.phone]){
        [Tools alertWithTitle:@"温馨提示" andMessage:@"请输入正确的手机号码"];
        return;
    }else if (self.verify.length == 0){
        [Tools alertWithTitle:@"温馨提示" andMessage:@"请输入验证码"];
        return;
    }
    
    [self.view endEditing:YES];
    //弹出协议窗口
    [self popProtocolView];
    
}




-(void)postHttpRequest{

    [self hidProtocolView];  //隐藏协议框
    
    [self popShadeView];   //开始转圈
    
    //2.发送注册请求
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"account"] = self.account;
    parameters[@"password"] = self.password;
    parameters[@"tphone"] = self.phone;
    parameters[@"code"] = self.verify;
    
    ZYHRequest *request = [ZYHRequest new];
    [request postAsyncEncryptRequest:@"/main/regist.app" parameters:parameters success:^(id responseData) {
        
        NSString *result = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
        NSLog(@"result:%@",result);
        
        if ([result rangeOfString:@"account"].location != NSNotFound){
            
            NSString *valueAccount = [NSString stringWithFormat:@"%@,您好!",self.account];
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"注册成功!" message:valueAccount delegate:self cancelButtonTitle:@"马上去登录" otherButtonTitles:nil, nil];
            [alertView show];
            
        }else if ([result rangeOfString:@"错误"].location != NSNotFound){
            
            [Tools alertWithTitle:@"温馨提示" andMessage:result];
            
        }else if ([result rangeOfString:@"-99"].location != NSNotFound){
            
            [Tools alertWithTitle:@"温馨提示" andMessage:@"系统繁忙,请重新获取验证码"];
        }
        
        [self hidShadeView];  //停止转圈
        return ;
        
    } failure:^(NSError *error) {
        
        [self hidShadeView];  //停止转圈
        [Tools alertWithTitle:@"温馨提示" andMessage:@"网络超时,请稍后再试!"];
        return ;
    }];
    
}

#pragma mark 判断账号是否可用
-(void)verifyWithAccount:(NSString *)account{
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"account"] = account;
    
    ZYHRequest *request = [ZYHRequest new];
    //NSData *data = [request getSyncEncryptRequest:@"/main/checkAccount.app?" parameters:parameters];
    [request postAsyncEncryptRequest:@"/main/checkAccount.app" parameters:parameters success:^(id responseData) {
        
        NSString *result = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
        NSLog(@"result:%@",result);  //结果是-1表示签名不对
        
        if ([result isEqualToString:@"1"]) {
            self.account = account;
            self.verifyText.textField.enabled = YES;
            self.verifyButton.enabled = YES;
            
        }else{
            
            [Tools alertWithTitle:@"温馨提示" andMessage:@"账号已存在"];
            [self.accountText.textField becomeFirstResponder];
        }
        
    } failure:^(NSError *error) {
        
        [Tools alertWithTitle:@"温馨提示" andMessage:@"网络超时,请稍后再试!"];
    }];
    
    
}


-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (self.accountText.textField.text.length == 0) {
        [Tools alertWithTitle:@"温馨提示" andMessage:@"请输入账号"];
        [self.accountText.textField becomeFirstResponder];
        return NO;
    }
    [self.view endEditing:YES];
    return YES;
}


-(void)accountInputFinish{
    
    if (self.isComeBack) {
        return;
    }

    NSString *accountStr = [self.accountText.textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    if (accountStr.length == 0) {
        
        [self.accountText.textField becomeFirstResponder];
        
    }else{
        //发送请求，验证账号是否可用
        [self verifyWithAccount:accountStr];
    }
    
}


- (void)comeBack{
    self.isComeBack = YES;   //解决返回时死机问题
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark 弹出协议框
-(void)popProtocolView{
    
    CGFloat width = SCREEN_WIDTH - 20;
    CGFloat height = SCREEN_HEIGHT - 20;
    self.protocolView = [[UIView alloc]initWithFrame:CGRectMake(10, 10, width, height)];
    self.protocolView.backgroundColor = [UIColor whiteColor];
    self.protocolWindow = [UIApplication sharedApplication].keyWindow;
    [self.protocolWindow addSubview:self.protocolView];
    
    //用户协议Label
    CGRect aFrame = CGRectMake(0, 0, width, 40);
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:aFrame];
    titleLabel.text = @"  用户协议";
    titleLabel.textColor = [UIColor blueColor];
    [self.protocolView addSubview:titleLabel];
    
    //Line1
    UIView *line1 = [[UIView alloc]initWithFrame:CGRectMake(0, 40, width, 2)];
    line1.backgroundColor = [UIColor blueColor];
    [self.protocolView addSubview:line1];
    
    //对于中文，UIWebView支持得并不是很好
    NSString *path = [[NSBundle mainBundle]pathForResource:@"xieyi" ofType:@".txt"];
    //NSURL *url = [NSURL fileURLWithPath:path];
    int encoding;
    // utf-8 编码会在这里识别
    NSString *body = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"body:%@",body);
    if (body.length == 0) {       // 如果之前不能解码，现在使用 GBK 解码
        NSLog(@"CBK");
        encoding = 0x80000632;
        body = [NSString stringWithContentsOfFile:path encoding:encoding error:nil];
    }
    if (body.length == 0) {   // 如果之前不能解码，再使用 GB18030 解码
        NSLog(@"GBK18030");
        encoding = 0x80000631;
        body = [NSString stringWithContentsOfFile:path encoding:encoding error:nil];
    }

//    if (body.length != 0) {  //然后将它们装换为 UTF16 编码并覆盖原来的文件
//        
//        NSData *inData = [body dataUsingEncoding:NSUTF16StringEncoding];
//        [inData writeToURL:url atomically:YES];
    
//    }else{
//        NSLog(@"没有合适的编码");
//    }

    //内容webView
    aFrame.origin.y = 42;
    aFrame.size.height = height - 42 - 42;
    UIWebView *webView = [[UIWebView alloc]initWithFrame:aFrame];
    //[webView loadRequest:[NSURLRequest requestWithURL:url]];
    [webView loadHTMLString:body baseURL:nil];
    [self.protocolView addSubview:webView];
    
    //左边是button
    aFrame.origin.y = height - 40;
    aFrame.size.width = (width - 2)/2;
    aFrame.size.height = 40;
    UIButton *leftButton = [[UIButton alloc]initWithFrame:aFrame];
    [leftButton setBackgroundColor:[UIColor lightGrayColor]];
    [leftButton setTitle:@"是" forState:UIControlStateNormal];
    //[leftButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [self.protocolView addSubview:leftButton];
    //添加点击事件
    [leftButton addTarget:self action:@selector(postHttpRequest) forControlEvents:UIControlEventTouchUpInside];
    
    //右边否button
    aFrame.origin.x = width/2 + 1;
    UIButton *rightButton = [[UIButton alloc]initWithFrame:aFrame];
    [rightButton setBackgroundColor:[UIColor lightGrayColor]];
    [rightButton setTitle:@"否" forState:UIControlStateNormal];
    //[rightButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [self.protocolView addSubview:rightButton];
    //添加点击事件
    [rightButton addTarget:self action:@selector(hidProtocolView) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark 隐藏协议弹出框
-(void)hidProtocolView{
    
    self.protocolView.hidden = YES;
 
}



#pragma mark 弹出网络延时加载框
-(void)popShadeView{
    
    self.shadeView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.shadeView.backgroundColor = [UIColor blackColor];
    self.shadeView.alpha = 0.3;
    self.coverWindow = [UIApplication sharedApplication].keyWindow;
    [self.coverWindow addSubview:self.shadeView];
    
    //添加一个等待进度轮
    self.activity = [[UIActivityIndicatorView alloc]init];
    self.activity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    self.activity.color = [UIColor blueColor];
    CGPoint center = self.shadeView.center;
    center.y -= 50;
    self.activity.center = center;
    [self.activity startAnimating];
    [self.coverWindow addSubview:self.activity];
    
    //添加一个提示Label
    self.indicateLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.activity.frame)+10, SCREEN_WIDTH, 44)];
    self.indicateLabel.textAlignment = NSTextAlignmentCenter;
    self.indicateLabel.font = [UIFont systemFontOfSize:14];
    self.indicateLabel.textColor = [UIColor blueColor];
    self.indicateLabel.text = @"拼命加载中...";
    [self.coverWindow addSubview:self.indicateLabel];
    
}

#pragma mark 取消网络延时加载框
-(void)hidShadeView{
    
    self.shadeView.hidden = YES;
    self.indicateLabel.hidden = YES;
    [self.activity stopAnimating];
    
}

#pragma mark alertView代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex == 0) {
        [self.navigationController popViewControllerAnimated:YES];
    }

}


#pragma mark 注册键盘通知
-(void)viewWillAppear:(BOOL)animated{
    /*
     UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 480}, {320, 253}}";
     UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 227}, {320, 253}}";
     */
    [super viewWillAppear:animated];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(openKeyboard:) name:UIKeyboardDidShowNotification object:nil];
    [center addObserver:self selector:@selector(closeKeyboard:) name:UIKeyboardWillHideNotification object:nil];
    
}

//键盘弹起时
-(void)openKeyboard:(NSNotification *)notification{
    
    if (IS_IPHONE4) {
        self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, 529+40);
        
    }else if (IS_IPHONE5) {
        self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, 441 + 40);

    }else if (IS_IPHONE6) {
        self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, 370 + 40);
        
    }
    
}

//键盘收起时
-(void)closeKeyboard:(NSNotification*)notification{
    
    self.scrollView.contentSize =  CGSizeMake(SCREEN_WIDTH, 336);
}


@end
